// 信息弹窗组件：从下往上出现，显示传入的卡片详情
import React from "react";
import { useNavigate } from "react-router-dom";
import { useI18n } from '@/utils/in18';
import { request } from '@/utils/request';
import InformationList from './information_list';

type Props = {
  visible: boolean;
  onClose: () => void;
  card?: {
    id: number;
    title: string;
    desc?: string;
    src?: string;
    raw?: any;
    role_prompt?: string;
  } | null;
};

// 将字符串按显示宽度截断：全角字符(中/日等)按2，半角字符(英文等)按1
const isFullWidthChar = (ch: string): boolean => {
  try {
    return /[\u1100-\u115F\u2E80-\uA4CF\uAC00-\uD7A3\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE6F\uFF00-\uFF60\uFFE0-\uFFE6]/u.test(ch);
  } catch {
    return false;
  }
};

const sliceByDisplayWidth = (input: string, maxFullWidthChars: number): string => {
  const source = input || '';
  const maxUnits = Math.max(0, maxFullWidthChars) * 2; // 7个中文 => 14半角单位
  let used = 0;
  let out = '';
  for (const ch of source) {
    const w = isFullWidthChar(ch) ? 2 : 1;
    if (used + w > maxUnits) break;
    out += ch;
    used += w;
  }
  return out === source ? out : out + '…';
};

// InformationCard 信息弹窗：负责头部主图、基本信息、操作按钮、选项卡与预览（列表逻辑下放至子组件）
const InformationCard: React.FC<Props> = ({ visible, onClose, card = null }) => {
  // 子组件上报的作品数组（仅用于父级拼接预览列表与登录后滚动）
  const [listWorks, setListWorks] = React.useState<any[]>([]);
  // 监听第一个内容区域是否在视口中，用于展示底部固定按钮
  const firstAreaRef = React.useRef<HTMLDivElement | null>(null);
  // null = 未知（挂载后才计算），true/false = 可见/不可见
  const [firstAreaVisible, setFirstAreaVisible] = React.useState<boolean | null>(null);
  const rootRef = React.useRef<HTMLDivElement | null>(null);
  const [hasVisibilityChecked, setHasVisibilityChecked] = React.useState(false);
  const navigate = useNavigate();
  const { t } = useI18n();


  // 主图加载（用于骨架屏）
  const [mainImageLoaded, setMainImageLoaded] = React.useState<boolean>(false);

  // 角色详情描述（从 /api/template/getRoleDetailRoute 获取）
  const [roleDescription, setRoleDescription] = React.useState<string>('');

  // 打开弹窗或卡片变化时获取角色详情
  React.useEffect(() => {
    if (!visible || !card) return;
    try {
      const templateId = (card as any)?.raw?.id ?? (card as any)?.id ?? 0;
      if (!templateId) return;
      request
        .post('/api/template/getRoleDetailRoute', { id: templateId })
        .then((res) => {
          try {
            const desc = res?.data?.data?.description;
            if (typeof desc === 'string') {
              let parsed: any = null;
              try { parsed = JSON.parse(desc); } catch { }
              if (parsed && typeof parsed === 'object' && typeof parsed.PersonalProfile !== 'undefined') {
                setRoleDescription(String(parsed.PersonalProfile));
              } else {
                setRoleDescription(desc);
              }
            } else if (desc && typeof desc === 'object' && typeof (desc as any).PersonalProfile !== 'undefined') {
              setRoleDescription(String((desc as any).PersonalProfile));
            }
          } catch { }
        })
        .catch(() => { });
    } catch { }
  }, [visible, card]);

  // 选项卡：图片 / 视频（默认图片）
  const [activeTab, setActiveTab] = React.useState<'image' | 'video'>('image');

  // 预览大图状态与索引
  const [previewOpen, setPreviewOpen] = React.useState<boolean>(false);
  const [previewIndex, setPreviewIndex] = React.useState<number>(0);
  // 预览列表（包含主图 + works 图片）
  const previewList = React.useMemo(() => {
    const list: { id: string | number; src: string }[] = [];
    try {
      if (card?.src) list.push({ id: `main_${card.id}`, src: String(card.src) });
    } catch { }
    try {
      listWorks.forEach((w) => {
        if (w?.src) list.push({ id: w.id, src: String(w.src) });
      });
    } catch { }
    return list;
  }, [card, listWorks]);

  // “功能即将开放”提示状态与定时器
  const [showChatTip, setShowChatTip] = React.useState<boolean>(false);
  const [showVideoTip, setShowVideoTip] = React.useState<boolean>(false);
  // 视频功能等待开放弹窗
  const [showVideoComingSoon, setShowVideoComingSoon] = React.useState<boolean>(false);
  const chatTipTimerRef = React.useRef<number | null>(null);
  const videoTipTimerRef = React.useRef<number | null>(null);

  const showFeatureComing = (type: 'chat' | 'video') => {
    try {
      if (type === 'chat') {
        if (chatTipTimerRef.current) window.clearTimeout(chatTipTimerRef.current);
        setShowChatTip(true);
        chatTipTimerRef.current = window.setTimeout(() => setShowChatTip(false), 2000);
      } else {
        if (videoTipTimerRef.current) window.clearTimeout(videoTipTimerRef.current);
        setShowVideoTip(true);
        videoTipTimerRef.current = window.setTimeout(() => setShowVideoTip(false), 2000);
      }
    } catch { }
  };

  // 组件卸载时清理提示定时器
  React.useEffect(() => {
    return () => {
      try {
        if (chatTipTimerRef.current) window.clearTimeout(chatTipTimerRef.current);
        if (videoTipTimerRef.current) window.clearTimeout(videoTipTimerRef.current);
      } catch { }
    };
  }, []);

  const openPreviewAt = (index: number) => {
    if (!previewList.length) return;
    const safeIndex = Math.max(0, Math.min(index, previewList.length - 1));
    setPreviewIndex(safeIndex);
    setPreviewOpen(true);
  };

  const openPreviewById = (targetId: string | number) => {
    if (!previewList.length) return;
    const idx = previewList.findIndex((p) => String(p.id) === String(targetId));
    openPreviewAt(idx >= 0 ? idx : 0);
  };

  const closePreview = () => setPreviewOpen(false);
  const goPrev = () => {
    if (!previewList.length) return;
    setPreviewIndex((i) => (i - 1 + previewList.length) % previewList.length);
  };
  const goNext = () => {
    if (!previewList.length) return;
    setPreviewIndex((i) => (i + 1) % previewList.length);
  };

  // 键盘左右与 ESC 支持（仅在预览打开时监听）
  React.useEffect(() => {
    if (!previewOpen) return;
    const onKey = (e: KeyboardEvent) => {
      try {
        if (e.key === 'ArrowLeft') {
          e.preventDefault();
          goPrev();
        } else if (e.key === 'ArrowRight') {
          e.preventDefault();
          goNext();
        } else if (e.key === 'Escape') {
          e.preventDefault();
          closePreview();
        }
      } catch { }
    };
    window.addEventListener('keydown', onKey as any);
    return () => {
      try { window.removeEventListener('keydown', onKey as any); } catch { }
    };
  }, [previewOpen, previewList.length]);

  // 列表点赞等逻辑已下放至子组件

  React.useEffect(() => {
    const el = firstAreaRef.current;
    if (!el) return;
    // 我们监听 body 上的可见性变更，通过计算元素的 getBoundingClientRect 来判断。
    const checkVisibility = () => {
      try {
        // 使用 RAF 保证浏览器布局已稳定
        window.requestAnimationFrame(() => {
          try {
            const rect = el.getBoundingClientRect();
            const viewportTop = 0;
            const viewportBottom = window.innerHeight || document.documentElement.clientHeight;
            // 如果元素高度为 0，视为不可见
            if (!rect.height) {
              setFirstAreaVisible(false);
              return;
            }
            // 计算元素与视口的交集高度（任何交集即视为可见）
            const intersectTop = Math.max(rect.top, viewportTop);
            const intersectBottom = Math.min(rect.bottom, viewportBottom);
            const intersectHeight = Math.max(0, intersectBottom - intersectTop);
            const visible = intersectHeight > 0; // 只要有可见像素即认为可见
            setFirstAreaVisible(visible);
          } catch (e) {
            // ignore
          }
        });
      } catch (e) {
        // ignore
      }
    };

    // 打开时先假定可见，避免初始闪现
    if (visible) {
      setFirstAreaVisible(true);
      setHasVisibilityChecked(false);
    }
    // 初始检查一次（不解锁 hasVisibilityChecked）
    checkVisibility();
    // 监听 window 与覆盖层自身的滚动与尺寸变化
    window.addEventListener('scroll', checkVisibility, { passive: true });
    const overlay = rootRef.current;
    if (overlay) {
      overlay.addEventListener('scroll', checkVisibility, { passive: true } as any);
    }
    window.addEventListener('resize', checkVisibility, { passive: true });
    const mo = new MutationObserver(checkVisibility);
    mo.observe(document.body, { childList: true, subtree: true, attributes: true });
    // 延迟一次检查，等过渡动画完成（280ms）后再允许渲染固定按钮
    const t = window.setTimeout(() => {
      checkVisibility();
      setHasVisibilityChecked(true);
    }, 380);
    return () => {
      window.removeEventListener('scroll', checkVisibility as any);
      if (overlay) {
        try { overlay.removeEventListener('scroll', checkVisibility as any); } catch { }
      }
      window.removeEventListener('resize', checkVisibility as any);
      mo.disconnect();
      window.clearTimeout(t);
    };
  }, [card, visible]);

  // 列表数据获取与懒加载已下放至子组件

  // 子组件会在 card/visible 变化时自行刷新，这里无需处理

  // 登录回跳后：根据保存的状态滚动到指定的作品位置（依赖列表渲染完成）
  React.useEffect(() => {
    if (!visible) return;
    try {
      const raw = sessionStorage.getItem('login:return_state');
      if (!raw) return;
      const state = JSON.parse(raw);
      if (state?.type !== 'infoCardMobile') return;
      const targetId = state?.restoreScrollToId;
      if (!targetId) return;
      // 等待当前帧渲染完毕再查询
      const tryScroll = () => {
        try {
          const container = rootRef.current;
          if (!container) return;
          const el = container.querySelector(`[data-work-id="${String(targetId)}"]`);
          if (el && (el as any).scrollIntoView) {
            (el as any).scrollIntoView({ behavior: 'smooth', block: 'center' });
            // 完成后清理状态，避免反复触发
            sessionStorage.removeItem('login:return_state');
          }
        } catch { }
      };
      // 使用两个 RAF 与一个超时，尽量确保列表已渲染
      requestAnimationFrame(() => requestAnimationFrame(tryScroll));
      setTimeout(tryScroll, 500);
    } catch { }
  }, [visible, listWorks]);

  // 懒加载滚动监听移动至子组件，父级不再处理

  // 弹窗不可见时不渲染具体内容，只保留容器以便过渡
  return (
    <div
      ref={rootRef}
      style={{ 
        width: '100vw', 
        zIndex: "99999", 
        height: '100vh',
        minHeight: '100vh',
        maxHeight: '100vh',
        overflow: 'hidden',
        position: 'fixed',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0
      }}
      aria-hidden={!visible}
      className={`pointer-events-none`}
    >
      {/* 半透明遮罩 */}
      <div
        onClick={onClose}
        className={`absolute inset-0 bg-black/40 transition-opacity ${visible ? "opacity-100 pointer-events-auto" : "opacity-0"}`}
        style={{ height: '100vh' }}
      />

      {/* 底部弹窗容器：从下往上过渡 */}
      <div
        className={`absolute left-0 right-0 bottom-0 flex justify-center`}
        style={{ pointerEvents: visible ? 'auto' : 'none' }}
      >
        {/* 弹窗容器 */}
        <div
          className={`w-full max-w-none bg-[#EDEDED] dark:bg-gray-800 shadow-lg transform transition-transform ${visible ? 'translate-y-0' : 'translate-y-full'
            }`}
          style={{ 
            width: '100vw', 
            height: '100vh',
            minHeight: '100vh',
            maxHeight: '100vh',
            paddingBottom: 'calc(env(safe-area-inset-bottom) + var(--tabbar-h, 0px))', 
            transitionDuration: '280ms', 
            willChange: 'transform',
            overflow: 'hidden',
            overflowY: 'auto',
            WebkitOverflowScrolling: 'touch'
          }}
        >
          {/* 弹窗内容 */}
          <div className="relative h-full flex flex-col">
            {/* 操作按钮区域  */}
            <div className="w-[98%] text-right mt-1 absolute z-10">
              <button onClick={onClose} className=" text-gray-500 dark:text-gray-300 p-1 rounded-full  bg-[#FCFCFC]">
                <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="4699" width="25" height="25"><path d="M240.512 180.181333l271.530667 271.488 271.530666-271.488a42.666667 42.666667 0 0 1 56.32-3.541333l4.010667 3.541333a42.666667 42.666667 0 0 1 0 60.330667l-271.530667 271.530667 271.530667 271.530666a42.666667 42.666667 0 0 1-56.32 63.872l-4.010667-3.541333-271.530666-271.530667-271.530667 271.530667-4.010667 3.541333a42.666667 42.666667 0 0 1-56.32-63.872l271.488-271.530666-271.488-271.530667a42.666667 42.666667 0 0 1 60.330667-60.330667z" fill="#515151" p-id="4700"></path></svg>
              </button>
            </div>
            {/* 卡片详情区域 - 可滚动内容 */}
            <div className="flex-1 overflow-y-auto" style={{ WebkitOverflowScrolling: 'touch' }}>
              {/* 被点击的卡片详情 */}
              {card ? (
                // content 内容区
                <div key={card.id} className="items-center">
                  {card.src && (
                    <div className="w-[98%] h-[30.96rem] m-auto cursor-zoom-in" onClick={() => openPreviewAt(0)}>
                      {/* 主图骨架：在图片未加载完成前显示灰色占位 */}
                      {!mainImageLoaded && (
                        <div className="w-full h-full rounded-xl bg-gray-200 dark:bg-gray-700 animate-pulse" />
                      )}
                      <img
                        key={card.id}
                        src={card.src || ''}
                        alt={card.title}
                        className={`w-full h-full object-cover object-top rounded-xl ${mainImageLoaded ? '' : 'hidden'}`}
                        onLoad={() => setMainImageLoaded(true)}
                        onError={() => setMainImageLoaded(true)}
                      />
                    </div>
                  )}
                  {/* 第一个内容区域  */}
                  <div ref={firstAreaRef} className="mt-4 w-[100%] m-auto dark:bg-[#2c2c2c] bg-white px-3 py-4 shadow-lg  items-start justify-between">
                    <div className="max-w-[100%]">
                      <div className="text-[1.5rem] dark:text-[white] text-gray-500 text-center font-semibold">{card.title}</div>
                      {(roleDescription || card.desc) ? (
                        <div className="mt-2 text-sm dark:text-gray-300 text-gray-600 text-left mx-auto">
                          {roleDescription || card.desc}
                        </div>
                      ) : null}
                    </div>
                    {/* 操作按钮：三项均匀分布，图标圆形，文字在下方 */}
                    <div className="mt-3 w-full flex justify-around items-start">
                      {/* 创建图片 */}
                      <div className="relative flex flex-col items-center text-center">
                        <button
                          onClick={() => {
                            try { onClose(); } catch (e) { }
                            try { navigate('/CreateImage', { state: { id: card?.id, name: card?.title, image_url: card?.src, role_prompt: card?.role_prompt || card?.raw?.role_prompt, category: card?.raw?.category || (card as any)?.category } }); } catch (e) { }
                          }}
                          className="w-12 h-12 rounded-full bg-[#EC4B9B] dark:bg-[#0A0907] text-white flex items-center justify-center"
                        >
                          <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="32105" width="20" height="20"><path d="M918.691833 149.924149H108.740166c-54.370083 0-98.44417 44.254719-98.44417 98.44417V803.810196c0 54.370083 44.254719 98.44417 98.44417 98.44417h809.951667c54.370083 0 98.44417-44.254719 98.44417-98.44417V248.368319c0-54.189451-44.074087-98.44417-98.44417-98.44417zM108.740166 214.590228h809.951667c18.605045 0 33.778091 15.173046 33.778091 33.778091v444.534133c-68.278709-106.391956-120.842477-174.851297-175.393191-184.244135-20.050097-3.431999-39.016405 1.445052-54.911977 14.089258l-2.890104 2.709472c-35.765038 36.487564-57.982713 71.530076-77.490916 102.418063-23.662727 37.390721-40.642089 64.304816-71.710707 77.310284-0.361263 0-13.1861-0.541895-42.809667-38.835773-23.843359-30.526724-48.951138-72.433233-75.503969-116.687952-30.887987-51.479979-62.859764-104.585641-94.83154-142.87952-35.945669-42.809667-73.155759-45.699771-98.082907-40.642089-73.697654 15.173046-137.641207 125.358264-183.70224 234.459693v-352.231434c-0.180632-18.605045 14.992415-33.778091 33.59746-33.778091z m809.951667 623.178691H108.740166c-18.605045 0-33.778091-15.173046-33.778092-33.778092v-10.83789C136.015523 590.303757 216.757806 441.282766 271.850415 429.902981c4.696419-0.903158 16.979361-3.431999 35.584406 18.785677 28.720409 34.319986 59.427765 85.25807 89.051332 134.570471 59.789028 99.527959 112.352796 187.31487 172.683718 187.31487 8.489681 0 16.979361-1.806315 25.830305-5.418945 49.854295-20.772623 74.962074-60.330923 101.514906-102.418063 17.521256-27.63662 37.21009-58.885871 67.19492-89.95449 0.722526-0.361263 1.445052-0.361263 2.528841-0.180631 38.835774 6.683366 116.326689 130.054683 162.568354 203.932969 7.767155 12.282942 15.173046 24.204622 22.578938 35.765038-3.61263 14.45052-16.979361 25.469042-32.694302 25.469042z" fill="#ffffff" p-id="32106"></path><path d="M764.071265 471.086964c61.053449 0 110.546481-49.673664 110.546481-110.546481s-49.673664-110.546481-110.546481-110.546481-110.546481 49.673664-110.546481 110.546481 49.673664 110.546481 110.546481 110.546481z m0-156.426883c25.288411 0 45.880402 20.591992 45.880402 45.880402 0 25.288411-20.591992 45.880402-45.880402 45.880403s-45.880402-20.591992-45.880402-45.880403c0-25.288411 20.591992-45.880402 45.880402-45.880402z" fill="#ffffff" p-id="32107"></path></svg>
                        </button>
                        <div className="mt-2 text-sm dark:text-gray-300 text-gray-600">{t('informationCard.make_image')}</div>
                      </div>

                      {/* 对话 */}
                      <div className="relative flex flex-col items-center text-center">
                        <button
                          onClick={() => showFeatureComing('chat')}
                          className="w-12 h-12 rounded-full bg-[#EC4B9B] dark:bg-[#0A0907] text-white flex items-center justify-center"
                        >
                          <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="23080" width="20" height="20"><path d="M512 457.031816A55.033029 55.033029 0 1 0 567.033029 512.064845 55.033029 55.033029 0 0 0 512 457.031816z m220.132117 0A55.033029 55.033029 0 1 0 786.738533 512.064845a55.033029 55.033029 0 0 0-55.033029-55.033029z m-439.837621 0A55.033029 55.033029 0 1 0 346.900913 512.064845a55.033029 55.033029 0 0 0-55.03303-55.033029z" fill="#ffffff" p-id="23081"></path><path d="M917.70861 637.062345a405.70861 405.70861 0 0 1-93.854778 127.983789A442.823909 442.823909 0 0 1 682.645052 853.354948a475.246469 475.246469 0 0 1-324.225598 7.252415 35.835461 35.835461 0 0 0-29.436272 2.986288L213.37116 929.718609l-18.344343-154.860384a35.835461 35.835461 0 0 0-10.238703-20.904019 389.923943 389.923943 0 0 1-115.18541-274.738533 378.832015 378.832015 0 0 1 34.12901-157.846673 405.70861 405.70861 0 0 1 93.854778-127.983789A442.823909 442.823909 0 0 1 341.354948 104.223172a474.393244 474.393244 0 0 1 343.849779 0 441.117458 441.117458 0 0 1 138.649105 87.882201 406.135223 406.135223 0 0 1 93.854778 127.983789 380.111852 380.111852 0 0 1 0 315.266733zM981.273892 291.932729a476.099694 476.099694 0 0 0-110.492671-152.300709 511.935155 511.935155 0 0 0-160.406348-102.387031 546.91739 546.91739 0 0 0-396.749746 0 511.935155 511.935155 0 0 0-162.539411 102.387031A478.232757 478.232757 0 0 0 42.726108 291.932729a451.782774 451.782774 0 0 0-42.661263 187.282944 461.168252 461.168252 0 0 0 127.983789 316.119958l23.037082 196.668422a36.262073 36.262073 0 0 0 35.835461 31.995947 36.262073 36.262073 0 0 0 17.91773-4.692739l148.461195-85.322526a547.344003 547.344003 0 0 0 358.354608-13.651604 511.935155 511.935155 0 0 0 162.539412-102.387031A477.806145 477.806145 0 0 0 981.273892 666.925229a453.915837 453.915837 0 0 0 0-374.9925z" fill="#ffffff" p-id="23082"></path></svg>
                        </button>
                        <div className="mt-2 text-sm dark:text-gray-300 text-gray-600">{t('informationCard.make_chat')}</div>
                        {showChatTip && (
                          <div className="absolute -top-12 z-10 left-1/2 -translate-x-1/2 pointer-events-none">
                            <div className="relative bg-black text-white text-xs py-1.5 px-3 rounded shadow-lg whitespace-nowrap w-max max-w-[90vw]">
                              {t('informationCard.coming_soon')}
                              <div className="absolute left-1/2 -translate-x-1/2 -bottom-1 w-2 h-2 bg-black rotate-45" />
                            </div>
                          </div>
                        )}
                      </div>

                      {/* 创建视频 */}
                      <div className="relative flex flex-col items-center text-center">
                        <button
                          onClick={() => showFeatureComing('video')}
                          className="w-12 h-12 rounded-full bg-[#EC4B9B] dark:bg-[#0A0907] text-white flex items-center justify-center"
                        >
                          <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="2510" width="20" height="20"><path d="M957.952 270.08v495.36c0 112.384-91.136 203.52-203.52 203.52h-495.36c-112.384 0-203.52-91.136-203.52-203.52V270.08c0-112.64 91.136-203.52 203.52-203.52h495.36c112.256 0 203.52 90.88 203.52 203.52z" fill="#53DEDC" p-id="2511"></path><path d="M957.952 270.08v52.608h-902.4V270.08c0-19.84 2.816-39.04 7.808-57.216 2.048-6.272 4.224-12.288 6.528-18.432 1.024-2.816 2.304-5.248 3.584-8.064 14.08-31.488 35.968-58.624 63.488-79.104 24.192-18.432 52.864-31.232 84.096-36.992 8.832-1.792 17.92-3.072 27.136-3.328 3.584-0.512 7.04-0.512 10.88-0.512h495.36c45.312 0 87.168 14.848 120.832 39.808 16.384 12.032 30.72 26.496 42.624 42.624 9.6 13.056 17.92 27.136 24.192 42.624 0.512 1.024 0.768 2.048 1.28 3.072 0.512 1.024 1.024 2.304 1.28 3.328 1.536 3.84 2.816 7.296 3.84 11.392 6.144 18.944 9.472 39.68 9.472 60.8z" fill="#FFFFFF" p-id="2512"></path><path d="M136.832 107.392c-27.392 20.352-49.408 47.616-63.488 79.104l-10.112 26.496c-4.992 18.176-7.808 37.248-7.808 57.216v52.608h40.832l128-128-87.424-87.424zM390.016 66.56H258.944c-3.84 0-7.296 0-10.88 0.512l127.488 127.488-128.128 128.128h142.336L517.888 194.56 390.016 66.56zM683.904 66.56H541.568l128 128-128.512 128.128h142.592L811.776 194.56zM948.352 209.152l-113.536 113.536h123.136V270.08c0-21.12-3.328-41.856-9.6-60.928z" fill="#282828" p-id="2513"></path><path d="M944.512 197.76H163.84v-6.272h778.24c0.512 1.024 0.768 2.048 1.28 3.072 0.384 0.896 0.896 2.176 1.152 3.2zM55.552 321.024h902.4v4.608h-902.4z" fill="#282828" p-id="2514"></path></svg>
                        </button>
                        <div className="mt-2 text-sm dark:text-gray-300 text-gray-600">{t('informationCard.make_video')}</div>
                        {showVideoTip && (
                          <div className="absolute -top-12 z-10 left-1/2 -translate-x-1/2 pointer-events-none">
                            <div className="relative bg-black text-white text-xs py-1.5 px-3 rounded shadow-lg whitespace-nowrap w-max max-w-[90vw]">
                              {t('informationCard.coming_soon')}
                              <div className="absolute left-1/2 -translate-x-1/2 -bottom-1 w-2 h-2 bg-black rotate-45" />
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>
                  {/* 选项卡菜单：图片 / 视频（默认选中图片） */}
                  <div className="w-[100%]">
                    {/* 选项卡菜单 */}
                    <div className="flex pt-2 dark:bg-[#2c2c2c] bg-white px-3">
                      <button
                        className={`${activeTab === 'image' ? 'text-[#EC4B9B] border-[#EC4B9B]' : 'text-gray-500 dark:text-gray-300 border-transparent'} mr-4 pb-2 border-b-2 transition-colors`}
                        onClick={() => setActiveTab('image')}
                      >{t('CreatImg.tab_image')}</button>
                      <button
                        className={`${activeTab === 'video' ? 'text-[#EC4B9B] border-[#EC4B9B]' : 'text-gray-500 dark:text-gray-300 border-transparent'} mr-4 pb-2 border-b-2 transition-colors`}
                        onClick={() => { setShowVideoComingSoon(true); }}
                      >{t('CreatImg.tab_video')}</button>
                    </div>
                    {/* 选项卡内容：图片 -> information_list；视频 -> 占位“敬请期待” */}
                    {activeTab === 'image' ? (
                      <InformationList
                        card={card}
                        visible={visible}
                        scrollContainerRef={rootRef}
                        onWorksChange={setListWorks}
                        onOpenPreviewById={openPreviewById}
                      />
                    ) : (
                      <div className="mt-1 w-[100%] m-auto dark:bg-[#2c2c2c] bg-white px-3 py-6 shadow-lg text-center text-gray-500 dark:text-gray-300">{t('informationCard.coming_soon')}</div>
                    )}
                  </div>
                </div>

              ) : (
                <div className="text-gray-500">{t('informationCard.no_content')}</div>
              )}
            </div>
          </div>
        </div>
      </div>

      {/* 顶层固定：当第一个内容区域不可见且已完成首检时显示制作按钮 */}
      {visible && hasVisibilityChecked && firstAreaVisible === false && (
        <div className="fixed left-0 right-0 bottom-[calc(env(safe-area-inset-bottom)+60px)] sm:bottom-4 flex justify-center pointer-events-none z-[100000]">
          <button
            onClick={() => {
              try { onClose(); } catch (e) { }
              try { navigate('/CreateImage', { state: { id: card?.id, name: card?.title, image_url: card?.src, role_prompt: card?.role_prompt || card?.raw?.role_prompt, category: card?.raw?.category || (card as any)?.category } }); } catch (e) { }
            }}
            className="pointer-events-auto relative bg-[rgb(236,75,155)] dark:bg-[#EC4B9B] text-white px-6 py-3 rounded-full transition duration-300 ease-out transform hover:scale-105 shadow-[0_0_8px_rgba(236,75,155,0.6),0_0_16px_rgba(236,75,155,0.35)] hover:shadow-[0_0_14px_rgba(236,75,155,0.9),0_0_28px_rgba(236,75,155,0.65)] focus:outline-none focus:ring-2 focus:ring-[rgba(236,75,155,0.55)] focus:ring-offset-2 focus:ring-offset-transparent"
            style={{ textShadow: '0 0 6px rgba(255,255,255,0.6), 0 0 10px #EC4B9B' }}
          >{t('informationCard.make_image')}</button>
        </div>
      )}

      {/* 大图预览弹窗 */}
      {previewOpen && (
        <div
          className="fixed inset-0 z-[100001] bg-black/80 flex items-center justify-center pointer-events-auto"
          onClick={closePreview}
          onWheel={(e) => { try { e.stopPropagation(); e.preventDefault(); } catch { } }}
          onTouchMove={(e) => { try { e.stopPropagation(); e.preventDefault(); } catch { } }}
        >
          {/* 图片区域 */}
          <div className="relative max-w-[94vw] max-h-[88vh]" onClick={(e) => { e.stopPropagation(); }}>
            <img
              src={previewList[previewIndex]?.src || ''}
              alt={String(previewList[previewIndex]?.id || '')}
              className="object-contain max-w-[94vw] max-h-[88vh] rounded"
            />

            {/* 左右切换按钮 */}
            <button
              aria-label="prev"
              onClick={(e) => { e.stopPropagation(); goPrev(); }}
              className="absolute left-2 top-1/2 -translate-y-1/2 p-2 rounded-full bg-[rgba(37,37,37,0.8)] hover:bg-white/30 text-white"
            >
              <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3471" width="24" height="24"><path d="M384 512L731.733333 202.666667c17.066667-14.933333 19.2-42.666667 4.266667-59.733334-14.933333-17.066667-42.666667-19.2-59.733333-4.266666l-384 341.333333c-10.666667 8.533333-14.933333 19.2-14.933334 32s4.266667 23.466667 14.933334 32l384 341.333333c8.533333 6.4 19.2 10.666667 27.733333 10.666667 12.8 0 23.466667-4.266667 32-14.933333 14.933333-17.066667 14.933333-44.8-4.266667-59.733334L384 512z" fill="#ffffff" p-id="3472"></path></svg>            </button>
            <button
              aria-label="next"
              onClick={(e) => { e.stopPropagation(); goNext(); }}
              className="absolute right-2 top-1/2 -translate-y-1/2 p-2 rounded-full bg-[rgba(37,37,37,0.8)] hover:bg-white/30 text-white"
            >
              <svg viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3681" width="24" height="24"><path d="M731.733333 480l-384-341.333333c-17.066667-14.933333-44.8-14.933333-59.733333 4.266666-14.933333 17.066667-14.933333 44.8 4.266667 59.733334L640 512 292.266667 821.333333c-17.066667 14.933333-19.2 42.666667-4.266667 59.733334 8.533333 8.533333 19.2 14.933333 32 14.933333 10.666667 0 19.2-4.266667 27.733333-10.666667l384-341.333333c8.533333-8.533333 14.933333-19.2 14.933334-32s-4.266667-23.466667-14.933334-32z" fill="#ffffff" p-id="3682"></path></svg>            </button>
            {/* 关闭按钮 */}
            <button
              aria-label="close"
              onClick={(e) => { e.stopPropagation(); closePreview(); }}
              className="absolute top-[0.5rem] right-[0.5rem] p-2 rounded-full bg-[rgba(37,37,37,0.8)] hover:bg-white/30 text-white"
            >
              <svg viewBox="0 0 1024 1024" width="22" height="22" xmlns="http://www.w3.org/2000/svg"><path fill="currentColor" d="M512 469.333l226.133-226.133 42.667 42.667L554.667 512l226.133 226.133-42.667 42.667L512 554.667 285.867 780.8l-42.667-42.667L469.333 512 243.2 285.867l42.667-42.667L512 469.333z" /></svg>
            </button>
          </div>
        </div>
      )}

      {/* 等待开放的弹窗  */}
      {showVideoComingSoon && (
        <div className='fixed inset-0 z-[1500] flex items-center justify-center px-6 pointer-events-auto'>
          <div className='absolute inset-0 bg-black/60 backdrop-blur-sm pointer-events-auto' onClick={() => { setShowVideoComingSoon(false); setActiveTab('image'); }} />
          <div className='relative z-10 w-full max-w-sm rounded-2xl border border-[#ff87bb66] bg-white/95 dark:bg-[#121214] shadow-xl p-8 text-center'>
            <div className='mx-auto mb-4 flex h-14 w-14 items-center justify-center rounded-full bg-gradient-to-br from-[#ec4899] to-[#f472b6] text-white text-2xl'>🎬</div>
            <div className='text-lg font-semibold text-[#2b2b2b] dark:text-[#fafafa]'>{t('CreatImg.video_coming_title')}</div>
            <p className='mt-2 text-sm text-[#6b7280] dark:text-[#9ea3a8]'>{t('CreatImg.video_coming_desc')}</p>
            <button
              onClick={() => { setShowVideoComingSoon(false); setActiveTab('image'); }}
              style={{ background: 'linear-gradient(to right, rgb(236, 72, 153), rgb(244, 114, 182), rgb(236, 72, 153))' }}
              className='mt-6 h-11 w-full rounded-lg text-sm font-medium text-white hover:opacity-90 transition-opacity'
            >
              {t('CreatImg.video_coming_button')}
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default InformationCard;


